package com.yuexiang.melodyhub.authserver.controller;

import com.yuexiang.melodyhub.authserver.dto.OAuthParseToken.response.OAuthParseTokenResponse;
import com.yuexiang.melodyhub.authserver.dto.OAuthRefreshToken.response.OAuthRefreshTokenResponse;
import com.yuexiang.melodyhub.common.constant.UsualConstant.BizConstant;
import com.yuexiang.melodyhub.common.result.ResultData;
import com.yuexiang.melodyhub.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/oauth/token")
public class TokenController {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("/refreshToken")
    public ResultData<OAuthRefreshTokenResponse> refreshToken(@RequestParam("email") String email, @RequestParam("token") String token) {
        String newToken = JwtUtil.refreshToken(token);
        redisTemplate.opsForValue().set(BizConstant.TOKEN_CACHE_PREFIX + email, newToken, BizConstant.TOKEN_CACHE_EXPIRE_HOURS, TimeUnit.HOURS);
        return ResultData.success(new OAuthRefreshTokenResponse(newToken, JwtUtil.parseToken(newToken).getPayload().getExpiration().getTime()));
    }

    @GetMapping("/parseToken")
    public ResultData<OAuthParseTokenResponse> parseToken(@RequestParam("token") String token) {
        Jws<Claims> claimsJws = JwtUtil.parseToken(token);
        return ResultData.success(new OAuthParseTokenResponse(claimsJws.getPayload().getSubject(), claimsJws.getPayload().get("roles", List.class), claimsJws.getPayload().getExpiration().getTime()));
    }
}
